package cn.edu.nuc.weiboclient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oauth.signpost.OAuth;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import cn.edu.nuc.modle.WeiBoData;
import cn.edu.nuc.modle.WeiBoList;

import com.google.gson.Gson;

public class HomepageTimeLine extends ListActivity {

	private SharedPreferences prefs = null;
	private long pageTime = 0;
	private boolean isUpdating = false;
	private ListView listView = null;
	private WeiBoItemAdapter adapter = null;
	private List<WeiBoData> weiBoDatas = null;
	private int pageflag = 0;
	private int isEnd = 0;
	
	protected void onCreate(Bundle savedInstanceState) {
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		weiBoDatas = getWeiBoDatasByPagetime(pageTime);
		ImageButton launchOauth = (ImageButton) findViewById(R.id.mainNewId);
        launchOauth.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Intent intent = new Intent();
            	intent.setClass(HomepageTimeLine.this,Enter.class);
            	startActivity(intent);
            }
        });
        ImageButton broadcastTimelineButton = (ImageButton)findViewById(R.id.mainRefreshId);
        
        broadcastTimelineButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Map<String,String> keyValues = new HashMap<String,String>();
				keyValues.put("format", "json");
				keyValues.put("pageflag", "0");
				keyValues.put("pagetime", "0");
				keyValues.put("reqnum", "20");
				WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, prefs.getString(OAuth.OAUTH_TOKEN, ""), prefs.getString(OAuth.OAUTH_TOKEN_SECRET, ""));
				String result = weiBoClient.doGet(Constants.WeiBoApi.HOME_TIMELINE, keyValues);
				System.out.println("result--->" + result);
				Gson gson = new Gson();
				WeiBoList weiBoList = gson.fromJson(result, WeiBoList.class);
				System.out.println("weibolist---->" + weiBoList);
				Intent intent = new Intent();
				intent.setClass(HomepageTimeLine.this, HomepageTimeLine.class);
				startActivity(intent);
				
			}
		});
		adapter = new WeiBoItemAdapter(this, weiBoDatas);
		listView = getListView();
		listView.setAdapter(adapter);
		listView.setOnScrollListener(new OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
			}
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(firstVisibleItem + visibleItemCount == totalItemCount && !isUpdating && isEnd == 0){
					AsyncUpdateWeiBoDatasTask asyncUpdateWeiBoDatasTask = new AsyncUpdateWeiBoDatasTask();
					asyncUpdateWeiBoDatasTask.execute();
					System.out.println("begin update-------------");
				}
			}
		});
		pageflag = 1;
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {				
			}			
		});		
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem followsItem = menu.add(Menu.NONE, 1, 1, "Friends");
		MenuItem mainItem = menu.add(Menu.NONE, 0, 0, "ME");
		MenuItem friendsItem = menu.add(Menu.NONE, 2, 2, "Funs");
		MenuItem homepageItem = menu.add(Menu.NONE, 3, 3, "@ME");
		MenuItem otherUsersItem = menu.add(Menu.NONE,4, 4, "LoginInterface");
		MenuItem usermentionedItem = menu.add(Menu.NONE, 5, 5, "Exit");
		
		followsItem.setIcon(android.R.drawable.ic_menu_send);
		friendsItem.setIcon(android.R.drawable.ic_menu_more);
		homepageItem.setIcon(android.R.drawable.ic_menu_send);
		otherUsersItem.setIcon(android.R.drawable.ic_menu_more);
		usermentionedItem.setIcon(android.R.drawable.ic_menu_send);
		mainItem.setIcon(android.R.drawable.ic_media_rew);
		return super.onCreateOptionsMenu(menu);
	}
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if(item.getItemId() == 5){
			finish();
			System.exit(0);
		}
		else if(item.getItemId() == 1){
			Intent intent = new Intent();
			intent.setClass(this,FriendsTimeLineActivity.class);
			startActivity(intent);
		}
		else if(item.getItemId() == 2){
			Intent intent = new Intent();
			intent.setClass(this, FollowsTimeLine.class);
			startActivity(intent);
		}
		else if(item.getItemId() == 3){
			Intent intent = new Intent();
			intent.setClass(this, UsermentionedTimeLine.class);
			startActivity(intent);
		}
		else if(item.getItemId() == 4){
			Intent intent = new Intent();
			intent.setClass(this,WeiboClientActivity.class).setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		else if(item.getItemId() == 0){
			Intent intent = new Intent();
			intent.setClass(this,MyPostTimeLine.class);
			startActivity(intent);
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private List<WeiBoData> getWeiBoDatasByPagetime(long pageTime) {
		Map<String, String> keyValues = new HashMap<String, String>();
		keyValues.put("format", "json");
		keyValues.put("pageflag", pageflag + "" );
		keyValues.put("pagetime", pageTime + "");
		keyValues.put("reqnum", "20");
		
		WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY,
				Constants.CONSUMER_SECRET, prefs.getString(OAuth.OAUTH_TOKEN,
						""), prefs.getString(OAuth.OAUTH_TOKEN_SECRET, ""));
		String result = weiBoClient.doGet(Constants.WeiBoApi.HOME_TIMELINE,
				keyValues);
		System.out.println("result------->" + result);
		Gson gson = new Gson();
		WeiBoList weiBoList = gson.fromJson(result, WeiBoList.class);
		isEnd = weiBoList.getData().getHasnext();
		List<WeiBoData> weiBoDatas = weiBoList.getData().getInfo();
		WeiBoData weiBoData = weiBoDatas.get(weiBoDatas.size() - 1);
		this.pageTime = weiBoData.getTimestamp();
		return weiBoDatas;
	}
	class AsyncUpdateWeiBoDatasTask extends AsyncTask<Void, Void, List<WeiBoData>>{

		@Override
		protected List<WeiBoData> doInBackground(Void... params) {
			isUpdating = true;
			return getWeiBoDatasByPagetime(pageTime);
		}

		@Override
		protected void onPostExecute(List<WeiBoData> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			weiBoDatas.addAll(result);
			adapter.notifyDataSetChanged();
			isUpdating = false;
			System.out.println("end update--------------");
		}		
	}
	/*class ClickLListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			
			long weiboId = arg1.getId();
			
			intent.putExtra("weiboId", weiboId);
			intent.setClass(HomepageTimeLine.this, TweetView.class);
			startActivity(intent);
		}
		
	}*/
}
